package com.hst.web.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hst.core.dao.IORDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.entity.TDict;
import com.hst.web.base.entity.TCompanyEmployee;

@Service
public class PapersNumberUtils {

	private static IORDao dao;

	private static Map<String, String> papersType = null;

	/**
	 * @param code
	 *            证件号
	 * @param type
	 *            证件类型
	 * @param employeeCode
	 *            排除的人员号
	 * @return
	 * @throws Exception
	 */
	public static Boolean duplicate(String code, String type, String employeeCode) throws Exception {
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq, "papersType", type));
		querys.add(new ORQuery(Op.eq, "papersNumber", code));
		// querys.add(new ORQuery(Op.eq, "validflag", "1"));// 有效
		if (null != employeeCode)
			querys.add(new ORQuery(Op.neq, "employeeCode", employeeCode));
		List<TCompanyEmployee> list = dao.list(TCompanyEmployee.class, querys);
		if (list.size() > 0)
			throw new Exception("已存在重复的证件类型+证件号");
		return true;
	}

	public static List<TCompanyEmployee> getEmployee(String code, String type) {
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq, "papersType", type));
		querys.add(new ORQuery(Op.eq, "papersNumber", code));
		// querys.add(new ORQuery(Op.eq, "validflag", "1"));// 有效
		return dao.list(TCompanyEmployee.class, querys);
	}

	public static Boolean validate(String code, String type) throws Exception {
		if (papersType == null) {
			papersType = new HashMap<String, String>();
			dao.list(TDict.class, new ORQuery(Op.eq, "name", "papersType")).stream()
					.forEach((e) -> papersType.put(e.getText(), e.getId()));
		}
		if (!papersType.values().contains(type))
			throw new Exception("无效的证件类型");

		switch (type) {
		// 身份证
		case ConstantUtil.PAPERSTYPE_ID1:
			if (!isIDNumber(code))
				throw new Exception("身份证号码不合法");
			break;
		}
		return true;
	}

	/**
	 * 身份证号校验
	 * 
	 * @param IDNumber
	 * @return
	 */
	public static boolean isIDNumber(String IDNumber) {
		if (IDNumber == null || "".equals(IDNumber)) {
			return false;
		}
		// 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
		String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|"
				+ "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";

		boolean matches = IDNumber.matches(regularExpression);

		// 判断第18位校验值
		if (matches) {

			if (IDNumber.length() == 18) {
				try {
					char[] charArray = IDNumber.toCharArray();
					// 前十七位加权因子
					int[] idCardWi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
					// 这是除以11后，可能产生的11位余数对应的验证码
					String[] idCardY = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
					int sum = 0;
					for (int i = 0; i < idCardWi.length; i++) {
						int current = Integer.parseInt(String.valueOf(charArray[i]));
						int count = current * idCardWi[i];
						sum += count;
					}
					char idCardLast = charArray[17];
					int idCardMod = sum % 11;
					if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
						return true;
					} else {
						System.out.println("身份证最后一位:" + String.valueOf(idCardLast).toUpperCase() + "错误,正确的应该是:"
								+ idCardY[idCardMod].toUpperCase());
						return false;
					}

				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("异常:" + IDNumber);
					return false;
				}
			}

		}
		return matches;
	}

	public IORDao getDao() {
		return dao;
	}

	@Autowired
	public void setDao(IORDao dao) {
		PapersNumberUtils.dao = dao;
	}

}
